package cn.ilikes.tools.nosql.jpa.clients.handers;

import org.slf4j.Logger;

import cn.ilikes.tools.logs.Loggerfactory;
import cn.ilikes.tools.nosql.jpa.JPASQLPersistenUnitEnv;
import cn.ilikes.tools.nosql.jpa.SysConfigs;
import cn.ilikes.tools.nosql.jpa.clients.dataSources.AbDataSource;
import cn.ilikes.tools.nosql.jpa.clients.dataSources.JPASQLDataSourceException;
import cn.ilikes.tools.nosql.jpa.clients.dataSources.hbases.HbaseDataSource;
import cn.ilikes.tools.nosql.jpa.clients.handers.hbases.HbaseDataHander;

public class DefultDataHanderFactory extends DefultDataHanderFactoryImples implements IDataHanderFactory {

	private Logger logger = Loggerfactory.instance(DefultDataHanderFactory.class);

	private String jpa_dialect;

	private AbDataSource<?> dataSource;

	public DefultDataHanderFactory(JPASQLPersistenUnitEnv hbasePersistenUnitEnv) {
		super(hbasePersistenUnitEnv);

	}

	@Override
	public void init() {
		JPASQLPersistenUnitEnv persistenUnitEnv = getHbasePersistenUnitEnv();
		try {
			initDataSource(persistenUnitEnv);
		} catch (JPASQLDataHnaderException e) {
			e.printStackTrace();
		}

	}

	private void setDataSource(AbDataSource<?> dataSource) {
		this.dataSource = dataSource;
	}

	private void initDataSource(JPASQLPersistenUnitEnv persistenUnitEnv) throws JPASQLDataHnaderException {

		jpa_dialect = persistenUnitEnv.getPersistenceUnitMetadata().getProperties().getProperty(SysConfigs.jpa_dialect);
		Loggerfactory.info(logger, "Start Create " + persistenUnitEnv.getPersistenUnitName() + " '" + jpa_dialect + " dataSource ");
		if ("hbase".equals(jpa_dialect)) {
			try {
				AbDataSource<?> dataSource = new HbaseDataSource(persistenUnitEnv);
				dataSource.init();
				this.setDataSource(dataSource);
			} catch (JPASQLDataSourceException e) {
				e.printStackTrace();
			}
		} else
			throw new JPASQLDataHnaderException("jpa dialect " + jpa_dialect + " no support ! ");
	}

	@Override
	public void open() {
		Loggerfactory.info(logger, "Start Open Data Hander Factory ");
		dataSource.open();
	}

	@Override
	public void close() {

		dataSource.close();
		Loggerfactory.info(logger, "Defult Data Hander Factory   close success ! ");
	}

	@Override
	public AbDataHander createAbDataHander() throws JPASQLDataHnaderException {
		if ("hbase".equals(jpa_dialect)) {
			AbDataHander dataHander = new HbaseDataHander((HbaseDataSource) dataSource, getHbasePersistenUnitEnv());
			return dataHander;
		}
		throw new JPASQLDataHnaderException("jpa dialect " + jpa_dialect + " no support ! ");
	}

	@Override
	public boolean isOpen() {
		return dataSource.isOpen();
	}

}
